using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using NBusiness.Utilities;
using System.Reflection;
using System.ComponentModel.Design;
using System.Collections;
using System.Web.UI;

namespace NBusiness.Data.Web.Design
{
    public partial class EntityDataSourceConfiguration : Form
    {
        private DataSourceControl _control;
        private string _oldTypeName;

        private Type _SelectedType;
        public Type SelectedType
        {
            get { return _SelectedType; }
        }

        public EntityDataSourceConfiguration()
        {
            InitializeComponent();

            LoadBusinessObjectCombo();
        }

        public EntityDataSourceConfiguration(DataSourceControl control, string oldTypeName)
        {
            _control = control;
            _oldTypeName = oldTypeName;

            InitializeComponent();
            LoadBusinessObjectCombo();
        }

        private void LoadBusinessObjectCombo()
        {
            comboBoxBusinessObjects.Items.Clear();

            ITypeDiscoveryService discovery = null;
            if (_control.Site != null)
            {
                discovery = (ITypeDiscoveryService)_control.Site.GetService(typeof(ITypeDiscoveryService));

                ICollection types = discovery.GetTypes(typeof(IEntityCollection), true);

                foreach (Type t in types)
                {
                    if (!t.IsInterface && !t.IsAbstract)
                        comboBoxBusinessObjects.Items.Add(t);
                }
            }

            if (_oldTypeName != null && comboBoxBusinessObjects.Items.Count > 0)
            {
                foreach (Type t in comboBoxBusinessObjects.Items)
                {
                    if (t.ToString() == _oldTypeName)
                    {
                        comboBoxBusinessObjects.SelectedItem = t;
                        break;
                    }
                }
            }

            //Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

            //foreach (Plugin p in Plugin.GetPlugins(typeof(IBusinessObject), assemblies))
            //{
            //    if (!p.Type.IsAbstract && !p.Type.IsInterface)
            //    {
            //        comboBoxBusinessObjects.Items.Add(p.Type);
            //    }
            //}
        }

        private void comboBoxBusinessObjects_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = comboBoxBusinessObjects.SelectedIndex;
            _SelectedType = comboBoxBusinessObjects.Items[index] as Type;
        }
    }
}